<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DataView视图</title>
</head>
<body>
    <h1>DataView视图</h1>
    <h2>用来操作ArrayBuffer的接口</h2>

    <script>
        // 创建DataView
        const buffer = new ArrayBuffer(16);
        const view = new DataView(buffer);

        // 写入数据
        view.setInt8(0, 42);
        view.setInt16(1, 12345, true); // 小端字节序
        view.setFloat32(3, 3.14);
        view.setFloat64(7, 123.456);

        // 读取数据
        console.log(view.getInt8(0)); // 42
        console.log(view.getInt16(1, true)); // 12345
        console.log(view.getFloat32(3)); // 3.14
        console.log(view.getFloat64(7)); // 123.456

        // 实际应用示例
        // 1. 二进制文件解析器
        class BinaryParser {
            constructor(buffer) {
                this.view = new DataView(buffer);
                this.offset = 0;
            }

            readUint8() {
                const value = this.view.getUint8(this.offset);
                this.offset += 1;
                return value;
            }

            readInt16() {
                const value = this.view.getInt16(this.offset, true);
                this.offset += 2;
                return value;
            }

            readFloat32() {
                const value = this.view.getFloat32(this.offset, true);
                this.offset += 4;
                return value;
            }

            readString(length) {
                let result = '';
                for (let i = 0; i < length; i++) {
                    result += String.fromCharCode(this.readUint8());
                }
                return result;
            }
        }

        // 2. 网络数据包处理
        class PacketHandler {
            static createPacket(type, data) {
                const buffer = new ArrayBuffer(data.length + 2);
                const view = new DataView(buffer);
                
                view.setUint8(0, type);
                view.setUint8(1, data.length);
                
                const dataView = new Uint8Array(buffer, 2);
                dataView.set(data);
                
                return buffer;
            }

            static parsePacket(buffer) {
                const view = new DataView(buffer);
                const type = view.getUint8(0);
                const length = view.getUint8(1);
                const data = new Uint8Array(buffer, 2, length);
                
                return {
                    type,
                    length,
                    data
                };
            }
        }

        // 使用示例
        const packet = PacketHandler.createPacket(1, new Uint8Array([1, 2, 3, 4]));
        const parsed = PacketHandler.parsePacket(packet);
        console.log(parsed);
    </script>
</body>
</html> 